<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <header class="navbar">
      <div class="navbar-brand">
        <h1>薛之谦粉丝应援站</h1>
      </div>
      
      <div class="navbar-user">
        <div class="user-info" v-if="userInfo">
          <img :src="userInfo.avatar" alt="用户头像" class="user-avatar">
          <span class="user-nickname">{{ userInfo.nickname }}</span>
          <span v-if="isVip" class="vip-badge">VIP</span>
        </div>
        
        <nav class="nav-links">
          <router-link to="/home" class="nav-link active">首页</router-link>
          <router-link to="/vip" class="nav-link">VIP中心</router-link>
          <button @click="handleLogout" class="logout-btn">退出登录</button>
        </nav>
      </div>
    </header>
    
    <!-- 粉丝时长展示 -->
    <div class="fans-since-section">
      <div class="fans-since-card">
        <h2>亲爱的谦友</h2>
        <p>你已经喜欢薛之谦 <span class="years-count">{{ fansSinceYears }} 年</span> 啦！</p>
        <p class="join-date">加入时间：{{ formatDate(fansSince) }}</p>
        <div class="love-meter">
          <div class="love-bar">
            <div class="love-progress" :style="{ width: `${loveProgress}%` }"></div>
          </div>
          <span class="love-percentage">{{ loveProgress }}%</span>
        </div>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 标签切换 -->
      <div class="tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.key" 
          :class="['tab-btn', { active: currentTab === tab.key }]"
          @click="switchTab(tab.key)"
        >
          {{ tab.label }}
        </button>
      </div>
      
      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <div class="search-box">
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="搜索关键词..." 
            @keyup.enter="search"
            class="search-input"
          >
          <button @click="search" class="search-btn">搜索</button>
        </div>
        
        <div class="filter-options" v-if="currentTab === 'concerts'">
          <select v-model="ticketStatusFilter" @change="search" class="filter-select">
            <option value="all">全部状态</option>
            <option value="即将开售">即将开售</option>
            <option value="预售中">预售中</option>
          </select>
        </div>
      </div>
      
      <!-- 数据列表 -->
      <div class="data-list">
        <div v-if="loading" class="loading">加载中...</div>
        
        <div v-else-if="dataList.length === 0" class="empty-state">
          <p>暂无数据</p>
        </div>
        
        <div class="items-grid" v-else>
          <div 
            v-for="item in dataList" 
            :key="item.id" 
            class="item-card"
            @click="goToDetail(item.id, currentTab)"
          >
            <div class="item-image">
              <img :src="item.image || item.cover" :alt="item.title" />
            </div>
            
            <div class="item-content">
              <h3 class="item-title">{{ item.title }}</h3>
              
              <div v-if="currentTab === 'concerts'" class="item-info">
                <p><i class="icon">📅</i> {{ item.date }}</p>
                <p><i class="icon">📍</i> {{ item.location }}</p>
                <span class="status-badge" :class="item.ticketStatus === '预售中' ? 'presale' : 'coming'">
                  {{ item.ticketStatus }}
                </span>
              </div>
              
              <div v-else-if="currentTab === 'albums'" class="item-info">
                <p><i class="icon">📅</i> {{ item.releaseDate }}</p>
                <p><i class="icon">🎵</i> {{ item.tracks }} 首歌曲</p>
              </div>
              
              <div v-else-if="currentTab === 'newsongs'" class="item-info">
                <p><i class="icon">🎤</i> {{ item.artist }}</p>
                <p><i class="icon">📅</i> {{ item.releaseDate }}</p>
                <span class="status-badge" :class="item.status === '即将上线' ? 'coming-soon' : 'in-progress'">
                  {{ item.status }}
                </span>
              </div>
              
              <p class="item-description">{{ item.description }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="page-btn"
        >
          上一页
        </button>
        
        <div class="page-numbers">
          <span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
        </div>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage >= totalPages"
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore, useAppStore } from '../store/index';
import { getConcerts, getAlbums, getNewSongs, mockData } from '../api/index';

export default {
  name: 'HomeView',
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const appStore = useAppStore();
    
    // 状态
    const loading = ref(false);
    const dataList = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const keyword = ref('');
    const ticketStatusFilter = ref('all');
    
    // 标签配置
    const tabs = [
      { key: 'concerts', label: '演唱会' },
      { key: 'albums', label: '专辑' },
      { key: 'newsongs', label: '新歌预告' }
    ];
    
    // 从store获取数据
    const userInfo = computed(() => userStore.getUserInfo);
    const isVip = computed(() => userStore.getIsVip);
    const fansSince = computed(() => userStore.getFansSince);
    const currentTab = computed(() => appStore.getCurrentTab);
    
    // 计算粉丝时长（年数）
    const fansSinceYears = computed(() => {
      if (!fansSince.value) return 0;
      const now = new Date();
      const since = new Date(fansSince.value);
      const years = now.getFullYear() - since.getFullYear();
      const monthDiff = now.getMonth() - since.getMonth();
      return monthDiff < 0 || (monthDiff === 0 && now.getDate() < since.getDate()) 
        ? years - 1 
        : years;
    });
    
    // 计算爱进度（随机值，模拟）
    const loveProgress = computed(() => {
      // 基础进度为粉丝年数*10，最高100%
      let progress = fansSinceYears.value * 10;
      if (isVip.value) progress += 20; // VIP额外加20%
      return Math.min(progress, 100);
    });
    
    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(total.value / pageSize.value);
    });
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return d.toLocaleDateString('zh-CN');
    };
    
    // 切换标签
    const switchTab = (tabKey) => {
      appStore.setCurrentTab(tabKey);
      currentPage.value = 1;
      loadData();
    };
    
    // 搜索
    const search = () => {
      currentPage.value = 1;
      loadData();
    };
    
    // 切换页码
    const changePage = (page) => {
      if (page < 1 || page > totalPages.value) return;
      currentPage.value = page;
      loadData();
    };
    
    // 跳转到详情页
    const goToDetail = (id, type) => {
      router.push({ name: 'detail', params: { id, type } });
    };
    
    // 退出登录
    const handleLogout = () => {
      userStore.logout();
      router.push('/');
    };
    
    // 加载数据
    const loadData = async () => {
      loading.value = true;
      
      try {
        let response;
        
        // 根据当前标签加载对应的数据
        switch (currentTab.value) {
          case 'concerts':
            // 在模拟环境中，我们直接使用mock数据
            response = mockData.concerts();
            break;
          case 'albums':
            response = mockData.albums();
            break;
          case 'newsongs':
            response = mockData.newSongs();
            break;
          default:
            response = { data: { list: [], total: 0 } };
        }
        
        if (response.code === 200) {
          let list = response.data.list;
          
          // 应用筛选
          if (keyword.value) {
            list = list.filter(item => 
              item.title.toLowerCase().includes(keyword.value.toLowerCase()) ||
              (item.description && item.description.toLowerCase().includes(keyword.value.toLowerCase()))
            );
          }
          
          // 应用票务状态筛选
          if (currentTab.value === 'concerts' && ticketStatusFilter.value !== 'all') {
            list = list.filter(item => item.ticketStatus === ticketStatusFilter.value);
          }
          
          dataList.value = list;
          total.value = list.length;
        } else {
          console.error('Failed to load data:', response.message);
        }
      } catch (error) {
        console.error('Error loading data:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 组件挂载时加载数据
    onMounted(() => {
      userStore.initUserState();
      loadData();
    });
    
    return {
      userInfo,
      isVip,
      fansSince,
      fansSinceYears,
      loveProgress,
      currentTab,
      loading,
      dataList,
      total,
      currentPage,
      totalPages,
      keyword,
      ticketStatusFilter,
      tabs,
      formatDate,
      switchTab,
      search,
      changePage,
      goToDetail,
      handleLogout
    };
  }
};
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 顶部导航栏 */
.navbar {
  background: rgba(255, 255, 255, 0.95);
  padding: 1rem 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  backdrop-filter: blur(10px);
}

.navbar-brand h1 {
  color: #e63946;
  font-size: 1.5rem;
  margin: 0;
}

.navbar-user {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #e63946;
}

.user-nickname {
  font-weight: 500;
  color: #495057;
}

.vip-badge {
  background: #ffd700;
  color: #333;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: bold;
}

.nav-links {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.nav-link {
  color: #495057;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  background: #e63946;
  color: white;
}

.logout-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background: #5a6268;
}

/* 粉丝时长展示 */
.fans-since-section {
  padding: 2rem;
  display: flex;
  justify-content: center;
}

.fans-since-card {
  background: rgba(255, 255, 255, 0.9);
  padding: 2rem;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
  backdrop-filter: blur(10px);
}

.fans-since-card h2 {
  color: #e63946;
  margin-bottom: 1rem;
}

.years-count {
  font-size: 1.5rem;
  font-weight: bold;
  color: #e63946;
}

.join-date {
  color: #6c757d;
  margin-bottom: 1.5rem;
}

.love-meter {
  margin-top: 1rem;
}

.love-bar {
  width: 100%;
  height: 20px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.love-progress {
  height: 100%;
  background: linear-gradient(90deg, #e63946, #ffb703);
  transition: width 0.5s ease;
}

.love-percentage {
  color: #e63946;
  font-weight: bold;
}

/* 主内容区 */
.main-content {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

/* 标签切换 */
.tabs {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 2rem;
  background: rgba(255, 255, 255, 0.9);
  padding: 0.5rem;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.tab-btn {
  flex: 1;
  padding: 1rem;
  border: none;
  background: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.tab-btn:hover {
  background: rgba(230, 57, 70, 0.1);
  color: #e63946;
}

.tab-btn.active {
  background: #e63946;
  color: white;
}

/* 筛选区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  gap: 1rem;
}

.search-box {
  display: flex;
  gap: 0.5rem;
  flex: 1;
}

.search-input {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 1rem;
}

.search-btn {
  background: #e63946;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.search-btn:hover {
  background: #c1121f;
}

.filter-select {
  padding: 0.75rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 1rem;
}

/* 数据列表 */
.data-list {
  margin-bottom: 2rem;
}

.loading,
.empty-state {
  text-align: center;
  padding: 4rem;
  color: #6c757d;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.item-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.item-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.item-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.item-card:hover .item-image img {
  transform: scale(1.05);
}

.item-content {
  padding: 1.5rem;
}

.item-title {
  font-size: 1.25rem;
  margin-bottom: 1rem;
  color: #333;
}

.item-info {
  margin-bottom: 1rem;
}

.item-info p {
  margin: 0.5rem 0;
  color: #6c757d;
  font-size: 0.875rem;
}

.icon {
  margin-right: 0.5rem;
}

.status-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  margin-top: 0.5rem;
}

.status-badge.presale {
  background: #2a9d8f;
  color: white;
}

.status-badge.coming {
  background: #e9c46a;
  color: #264653;
}

.status-badge.coming-soon {
  background: #e63946;
  color: white;
}

.status-badge.in-progress {
  background: #6c757d;
  color: white;
}

.item-description {
  color: #495057;
  font-size: 0.875rem;
  line-height: 1.5;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #ced4da;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: #e63946;
  color: white;
  border-color: #e63946;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #495057;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .navbar {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
  }
  
  .navbar-user {
    flex-direction: column;
    width: 100%;
    gap: 1rem;
  }
  
  .nav-links {
    width: 100%;
    justify-content: center;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .items-grid {
    grid-template-columns: 1fr;
  }
  
  .main-content {
    padding: 1rem;
  }
  
  .fans-since-section {
    padding: 1rem;
  }
}
</style>